package com.yipingnai.blog.service;

import com.yipingnai.blog.mapper.TagsMapper;
import com.yipingnai.blog.model.Tags;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: jiangym
 * @Date: 2020/5/19 11:05
 */
@Service
public class TagsService {

    @Autowired
    TagsMapper tagsMapper;

    public List<Tags> getAllTags() {

        return tagsMapper.getAllTags();
    }

    @Transactional
    public boolean deleteTagById(Integer id) {

        //先把有这个标签的文章的标签中间表的行删除
        int result = tagsMapper.deleteArticleTid(id);
        //删除标签
        int result1 = tagsMapper.deleteTag(id);
        if (result1 > 0){
            return true;
        }
        return false;
    }

    @Transactional
    public Integer addTag(String tagName) {
        //先判断有没有
        if(tagsMapper.selectTagByName(tagName) != null){
            //有
            return -1;
        }
        //不存在就添加
        return tagsMapper.addTag(new Tags(null,tagName));
    }

    @Transactional
    public List<Tags> addTags(String[] dynamicTags) {
        List<Tags> list = new ArrayList<>();
        for (String tagName : dynamicTags) {
            //先查找是否本身存在
            Tags tags = tagsMapper.selectTagByName(tagName);
            if(tags != null){//存在就直接加入集合
                list.add(tags);
            }else{//不存在就插入标签对象并返回标签
                Tags tags1 = new Tags(null,tagName);
                tagsMapper.addTag(tags1);
                list.add(tags1);
            }
        }
        return list;
    }
}
